const express = require('express');
const cors = require('cors');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./config/swagger');// Swagger 配置文件
const { connectToDb } = require('./config/db'); // 导入数据库连接模块
// 导入路由
const objectRoutes = require('./routes/objectRoutes');
const authRoutes = require('./routes/authRoutes');
const uploadRoutes = require('./routes/uploadRoutes');

const fs = require('fs');
const path = require('path');

require('dotenv').config(); // 引入 dotenv

const app = express();
const port = process.env.PORT || 3000;

app.use(cors()); // 允许跨域
app.use(express.json()); // 解析 JSON 请求体

// 初始化数据库连接
connectToDb().catch(console.error);

// 确保上传目录存在
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}
// 让 `uploads` 目录中的文件可以通过 HTTP 请求访问
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 使用路由
app.use('/object', objectRoutes);
app.use('/auth', authRoutes);
app.use('/common', uploadRoutes);

// 使用 Swagger UI
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

app.listen(port, '0.0.0.0', () => {
  console.log(`Server is running at ${process.env.DEV_URL}`);
});
